package com.affectu.forum.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.Name;

import com.affectu.category.Category;
import com.affectu.dao.DAOBase;
import com.affectu.forum.Plate;
import com.affectu.user.User;

/**
 * Oct 7, 2008
 * 
 * @author daniel nathan
 */
@Name("forumIndexAction")
public class Index extends DAOBase {

	@SuppressWarnings("unchecked")
	@Factory(value = "forumIndexAction_plates", scope = ScopeType.PAGE)
	public List<Plate> getPlates() {
		List<Plate> plates = new ArrayList<Plate>();
		try {
			plates = em.createQuery("from Plate").list();
			if (null == plates || plates.size() == 0) {
				this.initPlates();
				plates = em.createQuery("from Plate").list();// this.getPlates();
				// // fetch
				// again
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return plates;
	}

	@SuppressWarnings("unchecked")
	public void initPlates() {
		try {
			List<Category> categorys = em.createQuery(
					"from Category c where c.level=:level").setInteger("level",
					1).list();
			User owner;
			owner = (User) em.createQuery(
					"from User u where u.nickName=:nickName").setParameter(
					"nickName", "admin").uniqueResult();
			if (owner == null) {
				owner = new User();
				owner.setNickName("admin");
				em.persist(owner);
			}

			for (Category cat : categorys) {
				Plate plate = new Plate();
				plate.setName(cat.getName());
				plate.setContent(cat.getName() + "...的简介");
				plate.setOwner(owner);
				plate.setCreateDate(new Date());
				em.persist(plate);
			}
			em.flush();
		} catch (Exception ex) {
			this.logException(ex);
		}

	}
}
